package cn.tarena.ht.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.tarena.ht.pojo.User;
import cn.tarena.ht.service.UserService;

@Controller
public class LogController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "/sysadmin/login/login";
	}
	
	@RequestMapping("/login")
	public String login(String userName,String password,Model model,HttpSession session) {
		if(userName.isEmpty() || password.isEmpty()) {
			model.addAttribute("errorInfo", "*用户名和密码不能为空");
			return "/sysadmin/login/login";
		}
		//获取subject对象（Shiro的唯一出入口）
		Subject subject = SecurityUtils.getSubject();
		//定义登陆令牌（将用户输入的用户信息包装成令牌）
		UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
		try {
			//通过subject进行登陆操作
			subject.login(token);
			//通过subject对象获取用户的真实信息，并存储于session域中
			User user = (User) subject.getPrincipal();
			subject.getSession().setAttribute("sessionUser", user);
			//若登陆成功，放行该用户的所有的请求
			return "redirect:/home.action";
		}catch(AuthenticationException a) {
			//表示登陆失败
			model.addAttribute("errorInfo", "用户名或者密码错误");
			a.printStackTrace();
			return "/sysadmin/login/login";
		}catch(Exception e) {
			//表示程序执行过程出现异常
			e.printStackTrace();
			model.addAttribute("erroeInfo", "发现未知错误，请联系管理员！");
			return "/sysadmin/login/login";
		}
		
		/*password = Md5HashTool.getPassword(userName, password);
		System.out.println(password);
		User user = userService.findUserByUP(userName,password);
		if(user == null) {
			model.addAttribute("errorInfo", "*用户名或密码有误");
			return "/sysadmin/login/login";
		}
		session.setAttribute("sessionUser", user);
		return "redirect:/home";*/
	}
	
	@RequestMapping("/logout")
	public String logout() {
		return "/sysadmin/login/login";
	}
}
